<?php
namespace Todo\Controller;
use Todo\Service\TokenService;
use Todo\Util\ExcelUtil;

class ApiController extends BaseController {
    protected $_limit = 1000;
    protected $_order = 'id DESC';
    protected $_slistField = true;
    protected $_page = 1;
    protected $_model;

    protected function _initialize(){
       parent::_initialize();

        $headers = getallheaders();
        if($headers['X-Token']){
            $this->_user = TokenService::getInstance()->getTokenUser($headers['X-Token']);
        }
        if($this->_user){
            define('UID', $this->_user['id']);
            define('TNT_ID', $this->_user['tnt_id']);
        }
    }

    /**
     * 单条数据信息
     */
    public function info(){
        $id = I('get.id');
        if(!$id) $this->apiError('参数不完整');

        $this->_loadModel();
        $data = $this->_model->keyFind($id);
        if(!$data) $this->apiError('数据不存在');

        $this->apiData($data);
    }

    /**
     * 分页查询
     */
    public function lists(){
        $this->_limit = 100;
        $data = $this->_list();
        $this->apiList($data);
    }

    /**
     * 查询全部
     */
    public function slist(){
        $this->_loadModel();
        $where = $this->_search();
        $this->_filter($where);
        $list = $this->_model->field($this->_slistField)->distinct(true)->where($where)->order($this->_order)->select();
        $this->apiData($list);
    }

    /**
     * 添加
     */
    public function add(){
        $this->insert();
    }

    /**
     * 新增
     */
    public function insert(){
        if(IS_GET) $this->apiError('必须使用POST请求!');

        $this->_loadModel();
        $this->_model->startTrans();
        if(method_exists($this->_model, 'insert')){
            $ret = $this->_model->insert();
        }else{
            $ret = ($this->_model->create() && $this->_model->add() !== false);
        }
        if($ret === false){
            $this->_model->rollback();
            $this->apiError('保存失败!'.$this->_model->getError());
        }else{
            $this->_model->commit();
            $this->apiSuccess('保存成功!');
        }
    }

    /**
     * 编辑
     */
    public function edit(){
        $this->update();
    }

    /**
     * 更新
     */
    public function update(){
        if(IS_GET) {
            $this->apiError('必须使用POST请求!');
        }

        $this->_loadModel();
        $this->_model->startTrans();
        if(method_exists($this->_model, 'update')){
            $id = I('post.'.$this->_model->getPk());
            $ret = $this->_model->update($id);
        }else{
            $ret = ($this->_model->create() && $this->_model->save() !== false);
        }
        if($ret === false){
            $this->_model->rollback();
            $this->apiError('更新失败!'.$this->_model->getError());
        }else{
            $this->_model->commit();
            $this->apiSuccess('更新成功!');
        }
    }

    /**
     * 启用，支持批量
     */
    public function enable(){
        if(IS_GET){
            $ids = I('get.id');
            if(!$ids)  $this->apiError('非法请求!');
        }else{
            $ids = I('post.id');
            if(!$ids)  $this->apiError('非法请求!');
        }
        if(is_string($ids)) $ids = explode(',', $ids);
        $this->_loadModel();
        $this->_model->startTrans();
        $total = 0;
        foreach ($ids as $id){
            $this->_model->enable($id) && $total ++;
        }
        if($total == 0){
            $this->_model->rollback();
             $this->apiError('启用了'. $total. '条数据');
        }
        $this->_model->commit();
         $this->apiSuccess('启用了'. $total. '条数据');
    }

    /**
     * 禁用，支持批量
     */
    public function disable(){
        if(IS_GET){
            $ids = I('get.id');
            if(!$ids)  $this->apiError('非法请求!');
        }else{
            $ids = I('post.id');
            if(!$ids)  $this->apiError('非法请求!');
        }
        if(is_string($ids)) $ids = explode(',', $ids);
        $this->_loadModel();
        $this->_model->startTrans();
        $total = 0;
        foreach ($ids as $id){
            $this->_model->disable($id)  && $total ++;
        }
        if($total == 0){
            $this->_model->rollback();
             $this->apiError('启用了'. $total. '条数据');
        }
        $this->_model->commit();
         $this->apiSuccess('禁用了'. $total. '条数据');
    }

    /**
     * 删除，支持批量
     */
    public function delete(){
        if(IS_GET){
            $ids = I('get.id');
            if(!$ids)  $this->apiError('非法请求!');
        }else{
            $ids = I('post.id');
            if(!$ids)  $this->apiError('非法请求!');
        }
        if(is_string($ids)) $ids = explode(',', $ids);
        $this->_loadModel();
        $this->_model->startTrans();
        $total = 0;
        foreach ($ids as $id){
            $this->_model->del($id)  && $total ++;
        }
        if($total == 0){
            $this->_model->rollback();
             $this->apiError('启用了'. $total. '条数据');
        }
        $this->_model->commit();
         $this->apiSuccess('删除了'. $total. '条数据');
    }

    /**
     * 审核
     */
    public function verify(){
        if(IS_GET){
            $ids = I('get.id');
            if(!$ids) $this->apiError('非法请求!');
        }else{
            $ids = I('post.id');
            if(!$ids) $this->apiError('非法请求!');
        }
        if(is_string($ids)) $ids = explode(',', $ids);

        $verifyData = array(
            'verify_status' => I('post.verify_status/d'),
            'verify_user'   =>auto_login(),
            'verify_time'   => auto_datetime(),
            'verify_reason' => I('post.verify_reason')
        );
        $this->_loadModel();
        $this->_model->startTrans();
        $total = 0;
        foreach ($ids as $id){
            $this->_model->where(array('id'=>$id))->save($verifyData)  && $total ++;
        }
        if($total == 0){
            $this->_model->rollback();
            $this->apiError('操作失败!');
        }
        $this->_model->commit();
        $this->apiSuccess('审核了'. $total. '条数据', $this->_list_url);
    }
    
    /**
     * 导入
     */
    public function imports(){
        $file = I('post.excel');
        if(!$file) $this->apiError("请先上传文件!");

        $file =  C('FILE_UPLOAD.rootPath').$file;
        if(!file_exists($file)) $this->apiError("文件未上传成功或被删除，请重新上传文件!");

        $excel = new ExcelUtil();
        $list = $excel->importExecl($file);
        if(!$list || count($list[0]['Content']) < 3) $this->apiError("文件解析失败或内容为空，请检查您的文件并重新上传!");
        $this->_loadModel();
        $this->_model->startTrans();
        $error = I('post.error/d',1);
        $exists = I('post.exists/d',1);
        $count = 0;
        foreach($list[0]['Content'] as $i=>$row){
            if($i > 2){
                $ret = $this->_model->importOne($row, $exists);
                if($ret) $count++; //导入一行成功
                else{ //导入一行数据失败
                    if($error == 1){//退出
                        $this->_model->rollback();
                        $this->apiError('第'.$i.'行发生错误:'.$this->_model->getError());
                    }
                }
            }
        }
        $this->_model->commit();
        $this->apiSuccess("成功导入多少".$count."条数据!");
    }

    /**
     * 导出
     */
    public function exports(){
        $this->_loadModel();
        $where = $this->_search();
        $this->_filter($where);
        $list = $this->_model->pageSelect($where, 0, 10000, $this->_order);
        $excel = new ExcelUtil();
        $this->_model->exports($list, $excel);
    }

    /**
     * 生成格式化JS
     */
    public function format(){
        $this->_loadModel();
        $where = $this->_search();
        $this->_filter($where);
        $list = $this->_model->pageSelect($where, 0, $this->_limit, $this->_order);
        $this->assign('list', $list);
        $this->assign('name', I('get.name', strtolower(CONTROLLER_NAME)));
        $this->assign('keyField', I('get.keyField', 'id'));
        $this->assign('valField', I('get.valField', 'title'));
        $this->display('./Common/View/Public/format.html', 'utf-8', 'application/javascript');
    }

    /**
     * 通用分页查询，默认查询1000条
     * @return array
     */
    protected function _list(){
        $this->_loadModel();
        $where = $this->_search();
        $this->_filter($where);
        $this->_pager();
        $total = $this->_model->pageCount($where);
        $list = $this->_model->pageSelect($where, $this->_page, $this->_limit, $this->_order);
        return array(
            'list' => $list,
            'total' => $total
        );
    }

    /**
    +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
    +----------------------------------------------------------
     * @access protected
    +----------------------------------------------------------
     * @param  string $name 数据对象名称
    +----------------------------------------------------------
     * @return HashMap
    +----------------------------------------------------------
     * @throws ThinkExecption
    +----------------------------------------------------------
     */
    protected function _search($name = '') {
        $this->_loadModel();
        $map = array('tnt_id' => TNT_ID);
        foreach ($this->_model->getDbFields() as $key => $val ) {
            if(isset($_REQUEST[$val]) && $_REQUEST[$val] != '') {
                $map[$val] = $_REQUEST[$val];
            }
        }
        return $map;
    }

    /**
     * 自定义查询条件
     * @param array &$where 丢生成的查询条件
     */
    protected function _filter(&$where){}

    /**
     * 设置grid的分页信息
     */
    protected  function _pager() {
        if (isset($_REQUEST['page']) && !empty($_REQUEST['page'])) {
            $this->_page = intval($_REQUEST['page']);
        }

        if (isset($_REQUEST['limit']) && !empty($_REQUEST['limit'])) {
            $this->_limit = intval($_REQUEST['limit']);
        }

        if (isset($_REQUEST['sort']) && !empty($_REQUEST['sort'])) {
            $this->_order = $_REQUEST['sort'];
            if (isset($_REQUEST['order']) && !empty($_REQUEST['order'])) {
                $this->_order .= ' ' . $_REQUEST['order'];
            }
        }
    }

    /**
     * 加载 Model
     *
     */
    protected function _loadModel() {
        if(!$this->_model) $this->_model = D('Todo/'.MODULE_NAME.'/'.CONTROLLER_NAME);
    }

    /**
     * 验证权限范围
     * @param string $scope
     * @return bool
     */
    protected function _checkAccess($scope=''){
        //必须要有令牌
        if(!$this->_token) {
            $token = I('post.token/s');
            if (!$token && $scope != 'public') $this->apiError('非法请求，令牌不能为空', 709);
            if($token) $this->_token = TokenService::getInstance()->getToken($token);
            if (!$this->_token && $scope != 'public') $this->apiError('非法令牌或者已经过期',709);
        }

        if(!$scope || $scope == 'public') return true;

        if(!TokenService::getInstance()->checkScope($this->_token['code'], $scope)) $this->apiError(TokenService::getInstance()->getError(), 708);

        return true;
    }
}